<!--
 * @Author: lizuoqun
 * @Date: 2022-09-11 15:09:48
 * @LastEditors: lizuoqun
 * @LastEditTime: 2022-09-11 15:41:59
 * @Description: 代码雨特效实现
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>code-rain</title>
</head>
<style>
  html {
    width: 100%;
    height: 100%;
  }

  body {
    width: 100%;
    height: 100%;
    margin: 0;
  }
</style>

<body>
  <canvas id="bg"></canvas>
  <script>

    const bg = document.getElementById("bg")

    const width = window.innerWidth - 3
    const height = window.innerHeight - 5

    bg.width = width
    bg.height = height

    const ctx = bg.getContext("2d")
    ctx.fillStyle = 'rgba(1,1,1,0.9)'

    const colWidth = 15
    const colCount = Math.floor(width / colWidth)
    console.log(colCount)
    const colNextIndex = new Array(colCount)

    colNextIndex.fill(1)
    console.log(colNextIndex)

    function draw() {
      // ctx.fillStyle = 'rgba(240,240,240,0.1)'
      ctx.fillStyle = 'rgba(1,1,1,0.1)'
      ctx.fillRect(0, 0, width, height)
      const fz = 15
      ctx.fillStyle = getColor()
      ctx.font = `${fz}px "FangSong"`
      for (let i = 0; i < colCount; i++) {
        const x = i * colWidth
        const y = fz * colNextIndex[i]
        ctx.fillText(getFont(), x, y)
        if (y > height && Math.random() > 0.95) {
          colNextIndex[i] = 0
        } else {
          colNextIndex[i]++
        }
      }
    }

    function getColor() {
      // const colors = [
      //   '#ee4863',
      //   '#ee4863',
      //   '#45b787',
      //   '#fcc307',
      //   '#835e1d',
      //   '#f34718',
      //   '#b4a992'
      // ]
      const colors = ['#45b787']
      return colors[Math.floor(Math.random() * colors.length)]
    }

    function getFont() {
      // const str = '君不见黄河之水天上来奔流到海不复回'
      const str = 'qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890'
      return str[Math.floor(Math.random() * str.length)]
    }

    draw()
    setInterval(draw, 40);
  </script>
</body>

</html>